package org.opens.protobuf.test;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * 功能描述
 *
 * @author: zhangyuming
 */
@Data
public class ByteStringNodeHelper {

    public ByteStringNodeHelper(String savePath) {
        this.savePath = savePath;
    }

    private String savePath;

    private Map<String, List<ByteStringNode>> cacheData = new HashMap<>();

    private Map<String, Integer> cacheSizeData = new HashMap<>();

    public void addByteStringNode(String key, int size, ByteStringNode data) {
        if (!cacheData.containsKey(key)) {
            cacheData.put(key, new ArrayList<>(size));
            cacheSizeData.put(key, size);
        }

        List<ByteStringNode> byteStringNodes = cacheData.get(key);
        byteStringNodes.add(data);

        if (isComplete(key)) {
            saveToFile(key);
            cacheData.remove(key);
            cacheSizeData.remove(key);
        }
    }

    public boolean isComplete(String key) {
        if (!cacheData.containsKey(key)) {
            return false;
        }
        List<ByteStringNode> byteStringNodes = cacheData.get(key);
        Integer size = cacheSizeData.get(key);
        return Objects.equals(byteStringNodes.size(), size);
    }

    public void saveToFile(String key) {
        if (!cacheData.containsKey(key)) {
            throw new RuntimeException();
        }

        // 目录不存在则创建
        File file = new File(savePath);
        if (!file.exists()) {
            file.mkdirs();
        }

        try (FileOutputStream fos = new FileOutputStream(new File(savePath, "received_" + key + ".wav"))) {
            List<ByteStringNode> byteStringNodes = cacheData.get(key);
            byteStringNodes.sort(Comparator.comparing(ByteStringNode::getNo));
            for (ByteStringNode byteStringNodeItem : byteStringNodes) {
                fos.write(byteStringNodeItem.getData().toByteArray());
            }
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

}
